<script setup>
import { onMounted, ref, reactive, computed } from "vue";

let todos = ref([]);
let form = reactive({
  title: "",
  done: false,
});

const undone_count = computed(() => {
  return todos.length;
});

const fetchData = () => {
  fetch("http://127.0.0.1:5000/todo")
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      todos.value = data;
      console.log(todos);
    });
};

const add_todo = () => {
  fetch("http://127.0.0.1:5000/todo", {
    method: "post",
    body: JSON.stringify(form),
    headers: { "Content-Type": "application/json" },
  })
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      form.title = "";
      fetchData();
    });
};

const change_todo_status = (item) => {
  fetch(`http://127.0.0.1:5000/todo/${item.id}`, {
    method: "put",
    body: JSON.stringify(item),
    headers: { "Content-Type": "application/json" },
  })
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      console.log(data);
    });
};

const delete_todo = (item) => {
  fetch(`http://127.0.0.1:5000/todo/${item.id}`, {
    method: "delete",
    body: JSON.stringify(item),
    headers: { "Content-Type": "application/json" },
  })
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      console.log(data);
      fetchData();
    });
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="container mt-3">
    <div class="row">
      <div class="col-6 m-auto">
        <form action="/add_todo" method="post">
          <div class="input-group mb-3">
            <input
              type="text"
              class="form-control"
              placeholder="请输入任务"
              name="title"
              @keyup.enter="add_todo"
              v-model="form.title"
            />
            <button
              type="submit"
              class="btn btn-primary"
              @click.prevent="add_todo"
            >
              添加事项
            </button>
          </div>
        </form>
      </div>
    </div>
    <div class="row">
      <div class="col-6 m-auto">
        <div class="list-group mb-3">
          <label class="list-group-item" v-for="todo in todos">
            <input
              class="form-check-input me-1 todo-input"
              type="checkbox"
              :checked="todo.done"
              value="{{todo.id}}"
              @change="change_todo_status(todo)"
            />
            <span class="text-muted">{{ todo.title }}</span>
            <a class="text-decoration-none float-end" @click="delete_todo(todo)"
              >删除</a
            >
          </label>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
